<?php

class Admin_SezonaPresenter extends BasePresenter
{	
	public function renderDefault()
	{
		$sezona = new SezonaModel();
		$this->template->sezony = $sezona->findAll();
	}
	public function renderNovy()
	{
		$form = $this['sezonaForm'];
	}
	
	public function renderUpravit($id = 0)
	{
		$form = $this['sezonaForm'];
		if (!$form->isSubmitted()) {
			$sezona = new SezonaModel();
			$row = $sezona->findById($id)->fetch();
			if (!$row) {
				throw new NBadRequestException('Záznam nebyl nalezen.');
			}
			$form->setDefaults($row);
		}
	}
	
	public function renderSmazat($id = 0)
	{
		$form = $this['smazatForm'];
		$sezona = new SezonaModel();
		$soutez = new SoutezModel();
		$this->template->sezona = $sezona->findById($id)->fetch();
		
		//Je tato sezóna přiřazena nějaké soutěži?
		$sezona_in_soutez = $soutez->findBySezonaId($id)->fetchPairs('id','sezona_id');
		if(count($sezona_in_soutez) > 0)
			$this->template->enable_del = false;
		else
			$this->template->enable_del = true;
	
		
		if (!$this->template->sezona) {
			throw new NBadRequestException('Sezona nebyla nalezena');
		}
	}
	
	protected function createComponentSmazatForm()
	{
		$form = new NAppForm;
		
		$form->addSubmit('delete', 'Smazat')->getControlPrototype()->class('default');
		$form->addSubmit('cancel', 'Zpět');
		$form->onSubmit[] = callback($this, 'smazatFormSubmitted');
		$form->addProtection('Potvrďte prosím tento formulář znovu.');
		$this->template->form = $form;
		return $form;
	}
	
	public function smazatFormSubmitted(NAppForm $form)
	{
		if ($form['delete']->isSubmittedBy()) {
			$sezona = new SezonaModel();
			$sezona->delete($this->getParam('id'));
			$this->flashMessage('Sezóna byla odstraněna.');
		}

		$this->redirect('default');
	}
	
	protected function createComponentSezonaForm()
	{
		$form = new NAppForm;
		$form->addText('nazev', 'Název sezóny:');
	
		$form->addSubmit('save', 'Uložit')->getControlPrototype()->class('default');
		$form->addSubmit('cancel', 'Zpět')->getControlPrototype()->class('cancel')->setValidationScope(NULL);
		$form->onSubmit[] = callback($this, 'sezonaFormSubmitted');

		$form->addProtection('Potvrďte prosím tento formulář znovu.');
		$this->template->form = $form;
		return $form;
	}
	public function sezonaFormSubmitted(NAppForm $form)
	{
		if ($form['save']->isSubmittedBy()) {
			$id = (int) $this->getParam('id');
			$sezona = new SezonaModel();
			if ($id > 0) {
				$sezona->update($id, $form->getValues());
				$this->flashMessage('Sezona byla upravena.');
			} else {
				
				$sezona->insert($form->getValues());
				
				$this->flashMessage('Sezona byla vytvořena.');
			}
		}

		$this->redirect('default');
	}

}

